package cn.wolfcode.wolf2w.search.service.impl;

import cn.wolfcode.wolf2w.common.core.utils.StringUtils;
import cn.wolfcode.wolf2w.search.api.domain.DestinationEs;
import cn.wolfcode.wolf2w.search.api.domain.StrategyEs;
import cn.wolfcode.wolf2w.common.core.constant.SecurityConstants;
import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.search.query.SearchQueryObject;
import cn.wolfcode.wolf2w.search.repository.StrategyEsRepository;
import cn.wolfcode.wolf2w.search.service.IStrategyEsService;
import cn.wolfcode.wolf2w.strategy.api.RemoteStrategyService;
import cn.wolfcode.wolf2w.strategy.api.domain.Strategy;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchPage;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StrategyEsServiceImpl implements IStrategyEsService {

    @Autowired
    private StrategyEsRepository repository;
    @Autowired
    private RemoteStrategyService remoteStrategyService;

    @Override
    public void save(StrategyEs strategy) {
        //strategy.setId(null);
        repository.save(strategy);
    }

    @Override
    public void update(StrategyEs strategy) {
        repository.save(strategy);
    }

    @Override
    public StrategyEs get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyEs> list() {
        List<StrategyEs> list = new ArrayList<>();
        Iterable<StrategyEs> all = repository.findAll();
        all.forEach(a -> list.add(a));
        return list;
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }


    @Override
    public Page<Strategy> queryByKeyWord(SearchQueryObject qo) {
        //步骤1：查询es数据-找到ids集合
        //方式1：原生Api：NativeSearchQueryBuilder--麻烦，放弃：功能强大，操作麻烦，使用多条件处理
        //方式2：使用JPA注解方式
        String kw = qo.getKeyword();
        //分页--分页参数对象： 参数1：当前页，从0开始， 参数2：每页显示条数
        Pageable pageable  = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        SearchPage<StrategyEs> searchPage =  repository.queryByTitleOrSubTitleOrSummary(kw,kw,kw,pageable);
        SearchHits<StrategyEs> searchHits = searchPage.getSearchHits();

        List<Strategy> list = new ArrayList<>();  //当前页显示数据：
        for (SearchHit<StrategyEs> searchHit : searchHits) {
            String id = searchHit.getId();
            if(StringUtils.hasText(id)){
                R<Strategy> ret = remoteStrategyService.getOne(Long.parseLong(id), SecurityConstants.INNER);
                if(ret != null && R.isSuccess(ret)){
                    //步骤2：以id 作为条件查询mysql
                    Strategy strategy = ret.getData();
                    //高亮效果替换：
                    //searchHit 结果中： summary + subTitle + title
                    //替换从mysql查询的strategy对象中 summary + subTitle + title属性
                    StringUtils.handleESHighlight(searchHit.getHighlightFields(), strategy);

                    list.add(strategy);
                }
            }
        }
        //分页集封装
        return new PageImpl<>(list, pageable, searchPage.getTotalElements());
    }

    @Override
    public void initStrategyEs() {
        R<List<Strategy>> result = remoteStrategyService.list(SecurityConstants.INNER);
        List<Strategy> list = result.getData();

        List<StrategyEs> esList = list.stream().map(record -> {
            StrategyEs strategyEs = new StrategyEs();
            BeanUtils.copyProperties(record, strategyEs);

            return strategyEs;
        }).collect(Collectors.toList());

        repository.saveAll(esList);
    }
}
